package com.example.lizhanqi.livevideo.model.net;

import android.util.Log;

import com.example.lizhanqi.livevideo.presenter.IOnResultPresnter;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.CacheMode;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by Lizhanqi on 2016/9/14 0014.
 */
public class Networking {
    private static final String TAG = "李站旗";
    //传入P层的接口用来设置网络请求完成后的结果的设置,操作网络请求解析的结果
    IOnResultPresnter onResult;
    public Networking(IOnResultPresnter onResult) {
        this.onResult=onResult;
    }
    public void requestGET(String url, RequestQueue requestQueues, final int what) {
        //第二步：创建请求对象（url是请求路径， RequestMethod.POST是请求方式）
        Request<String> stringPostRequest = NoHttp.createStringRequest(url);
        stringPostRequest.setCacheMode(CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE);
        requestQueues.add(what, stringPostRequest, new SimpleResponseListener<String>() {
            @Override//请求成功的回调
            public void onSucceed(int i, Response<String> response) {
                Log.i(TAG, "N网络成功: ");
                onResult.ok(response,what);
            }
            @Override//请求失败的回调
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                Log.i(TAG, "N网络失败: ");
                onResult.error(i,s,o,e,i1,l);
            }
        });
    }

    public void requestPOST(String url, RequestQueue requestQueues, final int what, Map<String,String> body) {
        //第二步：创建请求对象（url是请求路径， RequestMethod.POST是请求方式）
        Request<String> stringPostRequest = NoHttp.createStringRequest(url, RequestMethod.POST);
        stringPostRequest.setCacheMode(CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE);
        if (body!=null){
            Set set = body.entrySet();
                Iterator iterator=set.iterator();
            while (iterator.hasNext() ){
                Map.Entry  mapentry = (Map.Entry) iterator.next();
                String key = (String) mapentry.getKey();
                String value = (String) mapentry.getValue();
                Log.i(TAG, "requestPOST: key:"+key+"value:"+value);
                stringPostRequest.add(key, value);
            }
        }
        requestQueues.add(what, stringPostRequest, new SimpleResponseListener<String>() {
            @Override//请求成功的回调
            public void onSucceed(int i, Response<String> response) {
                Log.i(TAG, "N网络成功: ");
                onResult.ok(response,what);
            }
            @Override//请求失败的回调
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                Log.i(TAG, "N网络失败: ");
                onResult.error(i,s,o,e,i1,l);
            }
        });
    }


}
